package com.control.qct.businesssteward.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.adapter.OrderAdapter;
import com.control.qct.businesssteward.base.BaseActivity;
import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.entity.TabEntity;
import com.control.qct.businesssteward.httputils.HttpUtils;
import com.control.qct.businesssteward.model.DoPayGoodsModel;
import com.control.qct.businesssteward.model.OrderListModel;
import com.control.qct.businesssteward.model.StoreModel;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lzy.okgo.OkGo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/1/9 0009.
 */

public class OrderActivity extends BaseActivity implements OnTabSelectListener, OrderAdapter.ICallbackClickListener,
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.ctl_replenishment_top)
    CommonTabLayout mCtlOrderTop;
    @BindView(R.id.rv_order)
    RecyclerView mRvOrder;
    @BindView(R.id.srl_refresh_order)
    SwipeRefreshLayout mSrlRefreshOrder;

    private final String[] mTitles = {"全部", "待收款", "已完成"};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private List<OrderListModel.DatasBean> mOrderModelList = new ArrayList<>();
    private OrderAdapter mOrderAdapter;
    private Map<String, String> mParams;
    private int mPageNum = 1;
    private int mState;
    private Bundle mBundle;
    private DoPayGoodsModel doPayGoodsModel = new DoPayGoodsModel();
    private static final int REQUEST_ORDER_DETAIL = 1001;
    private static final int REQUEST_GATHERING = 1002;
    private boolean mIsRefreshing;//判断是否处于下拉刷新

    public OrderActivity() {
        super(R.layout.activity_order);
    }

    @Override
    protected void initView() {
        setLeftIcon(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        setTitle("订单");
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], 0, 0));
        }
        mCtlOrderTop.setTabData(mTabEntities);
        mCtlOrderTop.setOnTabSelectListener(this);
        mBundle = new Bundle();
        //首次请求网络获取数据
        getOrderBeanList(0, true);
        mRvOrder.setLayoutManager(new LinearLayoutManager(this));
        mOrderAdapter = new OrderAdapter(mOrderModelList);
        mRvOrder.setAdapter(mOrderAdapter);
        mOrderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                doPayGoodsModel.setOrderId(mOrderAdapter.getData().get(position).getOrderId());
                doPayGoodsModel.setOrderSn(mOrderAdapter.getData().get(position).getOrderSn());
                doPayGoodsModel.setOrderAmount(mOrderAdapter.getData().get(position).getAmount());
                mBundle.putSerializable("order_information", doPayGoodsModel);
                mBundle.putString("orderSn", mOrderAdapter.getData().get(position).getOrderSnDisp());
                startActivityForResult(OrderDetailActivity.class, REQUEST_ORDER_DETAIL, mBundle);
            }
        });
        mOrderAdapter.setCallbackClickListener(this);//设置子列表点击回调
        mOrderAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_gathering://收款
                        if ((StoreModel) mSPUtils.getObject(mNetProtocol.getUserCode() + "_store") == null) {
                            showShortToast("未选择门店，请先选择门店！");
                            return;
                        }
                        doPayGoodsModel.setOrderId(mOrderAdapter.getData().get(position).getOrderId());
                        doPayGoodsModel.setOrderSn(mOrderAdapter.getData().get(position).getOrderSn());
                        doPayGoodsModel.setOrderAmount(mOrderAdapter.getData().get(position).getAmount());
                        mBundle.putSerializable("order_information", doPayGoodsModel);
                        mBundle.putInt("id", 1);
                        startActivityForResult(PaymentActivity.class, REQUEST_GATHERING, mBundle);
                        break;
                }
            }
        });
        mSrlRefreshOrder.setOnRefreshListener(this);//设置下拉刷新
        mSrlRefreshOrder.setColorSchemeColors(Color.parseColor("#05C1AB"), Color.parseColor("#FF66B7"), Color
                .parseColor("#FFBB43"));//设置下拉进度条主题颜色
    }

    @Override
    public void onTabSelect(int position) {
        mPageNum = 1;
        mOrderModelList.clear();
        mOrderAdapter.notifyDataSetChanged();
        mSrlRefreshOrder.setRefreshing(false);//设置取消刷新
        OkGo.getInstance().cancelTag(this);//切换时 如果上一个网络请求还未成功  取消该请求
        getOrderBeanList(position, true);
    }

    @Override
    public void onTabReselect(int position) {
    }

    @Override
    public void onLoadMoreRequested() {
        mPageNum++;
        getOrderBeanList(mState, false);
    }

    @Override
    public void onClickListener(int position) {
        doPayGoodsModel.setOrderId(mOrderAdapter.getData().get(position).getOrderId());
        doPayGoodsModel.setOrderSn(mOrderAdapter.getData().get(position).getOrderSn());
        doPayGoodsModel.setOrderAmount(mOrderAdapter.getData().get(position).getAmount());
        mBundle.putSerializable("order_information", doPayGoodsModel);
        mBundle.putString("orderSn", mOrderModelList.get(position).getOrderSnDisp());
        startActivity(OrderDetailActivity.class, mBundle);
    }

    /**
     * 获取订单详情
     */
    public void getOrderBeanList(int state, boolean isShow) {
        mState = state;
        mParams = new HashMap<>();
        mParams.put("state", state + "");
        mParams.put("pageNum", mPageNum + "");
        mParams.put("pageSize", "10");
        mNetProtocol.getSaleOrderList(this, mParams, isShow, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                if (mIsRefreshing) {
                    mOrderModelList.clear();
                    mIsRefreshing = false;
                    mOrderAdapter.setEnableLoadMore(true);
                }
                mSrlRefreshOrder.setRefreshing(false);//设置取消刷新
                OrderListModel orderListModel = (OrderListModel) baseBean.getData();
                mOrderModelList.addAll(orderListModel.getDatas());
                if (mOrderAdapter != null) {
                    if (orderListModel.getDatas().size() > 9) {
                        mOrderAdapter.setOnLoadMoreListener(OrderActivity.this, mRvOrder);
                        mOrderAdapter.loadMoreComplete();//加载完成
                    } else {
                        mOrderAdapter.loadMoreEnd();//加载结束 没有更多数据,不再去请求网络
                    }
                    mOrderAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_ORDER_DETAIL://跳转到订单详情 返回的
                case REQUEST_GATHERING://直接跳转到结算返回的
                    mPageNum = 1;
                    mOrderModelList.clear();
                    getOrderBeanList(mState, true);
                    break;
            }
        }
    }

    @Override
    public void onRefresh() {
        mPageNum = 1;
        mIsRefreshing = true;
        mOrderAdapter.setEnableLoadMore(false);
        getOrderBeanList(mState, false);
    }
}
